<template>
  <div>
    <el-dialog ref="dislogRef" :visible.sync="dialogVisible" lock-scroll width="1100px">
      <div slot="title" class="header_title">
        <span class="title_span">选择{{ propsData.invoiceCategory == 1 ? '商品' : '单据' }}</span>
      </div>
      <div class="content_div">
        <div class="div_screen">
          <div class="screen_left">
            <div class="custom_item">
              <div style="width:55px;">供应商</div>
              <div class="custom_select_head">
                <el-select
                  v-model="queryData.xghCompanyId"
                  style="width:100%;"
                  filterable
                  ref="deptSelect"
                  :filter-method="(value) => handleFilterMethod(gysOptions, value, 'companyName')"
                  disabled
                >
                  <el-option
                    v-for="item in gysOptions"
                    :key="item.id"
                    :label="item.companyName"
                    :value="item.id"
                  ></el-option>
                  <el-option key label value>
                    <div class="custom_add" @click.stop="onShowSupplierAdd">
                      <i class="el-icon-plus"></i>
                      <span>新增</span>
                    </div>
                  </el-option>
                </el-select>
                <div class="custom_more"> 
                  <!-- @click.stop="onShowSupplier" -->
                  <i class="el-icon-more" ></i>
                </div>
              </div>
            </div>
            <div class="custom_item">
              <div style="width:55px;">商品信息</div>
              <div class="custom_select_head">
                <el-input type="text" v-model="queryData.goodsName" placeholder="请输入" />
              </div>
            </div>
            <div class="custom_item" style="width: 220px;">
              <div style="width:55px;">单据编号</div>
              <div class="custom_select_head">
                <el-input type="text" v-model="queryData.orderNumber" placeholder="请输入" />
              </div>
            </div>
            <div class="custom_item">
              <div style="width:55px;">单据状态</div>
              <div class="custom_select_head">
                <j-dict-select-tag
                  type="select"
                  dictCode="order_query_status"
                  style="width:100%"
                  v-model="queryData.purchaseOrderStatus"
                  placeholder="请选择"
                ></j-dict-select-tag>
              </div>
            </div>
            <div class="custom_item">
              <div style="width:55px;">发票类型</div>
              <div class="custom_select_head">
                <!-- <j-dict-select-tag
                  type="select"
                  dictCode="invoice_type"
                  style="width:100%"
                  v-model="queryData.invoiceCategory"
                  placeholder="请选择"
                ></j-dict-select-tag> -->
                <el-select v-model="queryData.invoiceType" style="width: 100%" filterable ref="deptSelect" placeholder="请选择">
                  <el-option
                    v-for="item in fpOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </div>
            </div>
          </div>
          <div class="screen_right">
            <!-- <div class="right_top"> -->
            <!-- <el-checkbox v-model="isData"></el-checkbox> -->
            <el-select v-model="monthValue" @change="changeDate">
              <el-option v-for="item in monthOptions" :key="item" :label="item" :value="item"></el-option>
            </el-select>
            <el-date-picker
              :disabled="!isData"
              v-model="nowDate"
              type="daterange"
              range-separator="~"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="onClickPicker"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
            <el-button type="primary" @click="getBillList">查询</el-button>
            <el-button class="button-refresh" @click="onRefresh">重置</el-button>
            <!-- </div>
            <div style="display: flex;margin-top: 20px;">-->
            <el-button
              class="btnSelect"
              @click="onSelectOrder"
              style="width: 64px;margin-left: 20px;background-color: #00BC64;color: #fff;"
              :loading="getDetailLoading"
            >{{ getDetailLoading ? '' : '选择' }}</el-button>

            <el-button
              class="btnSelect"
              @click="showDetailBill = !showDetailBill"
              style="margin-left: 20px;background-color: #FF9317;color: #fff;"
            >
              {{ showDetailBill ?
              '隐藏明细' : '显示明细' }}
            </el-button>
            <!-- </div> -->

            <el-checkbox v-model="queryData.isHideInvoice" style="margin-left: 20px" @change="queryClick"
                >隐藏已开发票单据</el-checkbox
              >
          </div>
        </div>
        <div style="height:500px;">
          <div :style="{ 'height': showDetailBill ? '50%' : '100%' }">
            <div class="danju">
              <div class="billsLeft">单据</div>
              <i @click="onShowColumn('list')" class="set_up el-icon-s-tools" :size="20"></i>
            </div>

            <!-- @row-dblclick="onDblClickRow" -->


            <el-table
              ref="singleTable"
              :data="listTableData"
              @row-click="onClickRow"
              :height="showDetailBill ? '210' : '470'"
              :show-summary="true"
              :summary-method="getSummaries"
              highlight-current-row
              @select="handleSingleSelectionChange"
              @select-all="handleSingleSelectAll"
            >
              <el-table-column type="selection" width="60" align="center" ></el-table-column>
              <el-table-column type="index" width="100" label="序号" align="center"></el-table-column>
              <template v-for="(item, i) in columnData">
                <el-table-column
                  :show-overflow-tooltip="true"
                  :key="i"
                  :prop="item.props"
                  v-if="item.zidingyiState"
                  :min-width="['orderNumber', 'createTime'].includes(item.props) ? '170px' : '120px'"
                  :label="item.zidingyiName ? item.zidingyiName : item.morenName"
                >
                  <template slot-scope="scope">
                    <div
                      v-if="item.props == 'purchaseOrderPrice' || item.props == 'payPrice' || item.props == 'allPrice' || item.props == 'rebatePrice' || item.props == 'receivablePrice' || item.props == 'owePrice' || item.props == 'orderAllPrice' || item.props == 'collectionPrice' || item.props == 'orderDiscountPrice'"
                    >{{ $formatMoney(scope.row[item.props]) }}</div>
                    <div v-else>{{ scope.row[item.props] }}</div>
                  </template>
                </el-table-column>
              </template>
            </el-table>
          </div>
          <div style="height: 50%;" v-if="showDetailBill">
            <div class="danju">
              <div style="display: flex;align-items: center;">
              <div class="billsLeft">单据明细</div>
              <el-checkbox v-model="queryData.isHideInvoiceInfo" style="margin-left: 20px" @change="queryClick"
                >已开发票明细不再显示</el-checkbox
              >
            </div>
              <i @click="onShowColumn('detail')" class="set_up el-icon-s-tools" :size="20"></i>
            </div>

            <el-table
              ref="multipleTable"
              :data="detailTableData"
              height="210"
              :show-summary="true"
              :summary-method="getSummaries1"
              @select="handleMultipleSelect"
              @select-all="handleMultipleSelectAll"
            >
              <el-table-column v-if="propsData.invoiceCategory == 1" type="selection" width="60" align="center"></el-table-column>
              <el-table-column type="index" width="100" label="序号" align="center"></el-table-column>
              <template v-for="(item, i) in detailColumnData">
                <el-table-column
                  :show-overflow-tooltip="true"
                  :key="i"
                  :prop="item.props"
                  v-if="item.zidingyiState"
                  :min-width="item.props == 'orderNumber' ? '170px' : '120px'"
                  :label="item.zidingyiName ? item.zidingyiName : item.morenName"
                >
                  <template slot-scope="scope">
                    <div
                      v-if="item.props == 'taxPrice' || item.props == 'costPrice' || item.props == 'allPrice' || item.props == 'allotPrice' || item.props == 'allotAllprice'"
                    >{{ $formatMoney(scope.row[item.props]) }}</div>
                    <div
                      v-else-if="item.props == 'number' || item.props == 'arrivalNumber' || item.props == 'notArrivalNumber'"
                    >{{ $formatNumber(scope.row[item.props]) }}</div>
                    <div
                      v-else-if="item.props == 'salePrice' || item.props == 'discountUnitPrice' || item.props == 'taxUnitPrice'"
                    >{{ $formatPrice(scope.row[item.props]) }}</div>
                    <div v-else>{{ scope.row[item.props] }}</div>
                  </template>
                </el-table-column>
              </template>
            </el-table>
          </div>
        </div>
      </div>
    </el-dialog>
    <!-- 列配置弹框-->
    <CConfiguration
      ref="setColumnRef"
      :columnDataArr="newColumnData"
      :defaultColumnDataArr="defaultColumnData"
      :orderType="propsData.title"
      @onSaveColumn="onSaveColumn"
    ></CConfiguration>
    <!-- 新增客户弹框 -->
    <DialogSupplierAdd ref="supplierAddRef" @onAddSubmit="onAddSupplier"></DialogSupplierAdd>
    <!-- 选择客户弹框 -->
    <DialogSupplier ref="supplierRef" @onSelectSupplier="onSelectSupplier"></DialogSupplier>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import billColumn from '@/utils/transferColumnConfiguration'
import CConfiguration from '@/components/c_column/columnConfiguration1'
import DialogSupplierAdd from './dialogSupplierAdd'
import DialogSupplier from './dialogSupplier'
import { handlePermissions, handleOtherPerms, getSystemParamsByName, formatMoney, formatPrice, formatNumber, delcommafy, handleArrayToObject, handleObjectToArray } from '@/utils/index'
import { getAction } from '../../api/manage'
import { getDictItemsFromCache } from '../../api/api'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
export default {
  name: 'BasicInformation',
  computed: {
    ...mapGetters(['name']),
  },
  mixins: [JeecgListMixin],
  components: {
    CConfiguration,
    DialogSupplierAdd,
    DialogSupplier
  },
  data () {
    return {
      propsData: {},
      showDetailBill: true,
      isData: true,
      nowDate: [],
      monthOptions: ['今日', '本周', '本月', '本年'],
      // 发票类型
      fpOptions:[
        {
          id: '1',
          label: '收据',
          value: 1,
        },
        {
          id: '2',
          label: '普通发票',
          value: 2,
        },
        {
          id: '3',
          label: '增值税发票',
          value: 3,
        },
        {
          id: '0',
          label: '全部显示',
          value: '',
        },
      ],
      // 供应商
      gysOptions: [],
      // 查询条件数据
      queryData: {
        isHideInvoice: true,
        isHideInvoiceInfo: false,
        xghCompanyId: '',
        orderNumber: '',
        invoiceType: '',
        purchaseOrderStatus: '5',
        goodsName: '',
        createTime_begin: '',
        createTime_end: ''
      },
      tableData: [],
      newColumnData: [],
      dialogVisible: false, // 新增弹框
      // 月份选择
      monthValue: '本月',
      defaultColumnData: [],
      columnData: [],
      detailColumnData: [],
      listUpdateId: '',
      detailUpdateId: '',
      listTableData: [],
      detailTableData: [],
      multipleSelection: [],
      multipleBillSelection: [], //多选单据
      currentRow: null,
      getDetailLoading: false,
      billType: '',
      columnSet: '', //设置的是单据还是明细
    }
  },
  created () {
    this.getGysStorage()
  },
  methods: {
    show (data) {
      this.propsData = data
      console.log("this.propsData",this.propsData);
      //获取默认列配置
      this.columnData = billColumn.columnData[this.propsData.title].list
      let detail = billColumn.columnData[this.propsData.title].detail
      this.detailColumnData = handleObjectToArray(detail)

      //恢复默认值
      this.showDetailBill = true
      this.isData = true
      this.getDetailLoading = false
      // this.multipleSelection = []
      // this.multipleBillSelection = []

      // this.queryData = this.$options.data().queryData
      this.queryData.xghCompanyId = data.xghCompanyId
      this.xghCompany = data.xghCompanyId

      this.nowDate = []
      //获取携带参数
      // this.billType = this.getBillType()
      this.billType = this.propsData.billType

      //
      let title = data.title
      // if (data.title == '采购订单' || data.title == '销售订单') {
      //   this.queryData.status = '0'
      // } 
      this.monthValue = '本月'
      this.getTimeRange(this.$setTimeRange(5))
      // 获取数据
      this.selectTitle()
      this.selectDetailTitle()
      this.getBillList()
      this.dialogVisible = true
    },
    hide () {
      this.dialogVisible = false
    },
    queryClick() {
      this.getBillList(1)
    },
    getParams () {
      let params = {
        xghCompanyId: this.queryData.xghCompanyId == 0 ? undefined : this.queryData.xghCompanyId,
        createTime_begin: this.isData ? this.queryData.createTime_begin : undefined,
        createTime_end: this.isData ? this.queryData.createTime_end : undefined,
        goodsName: this.queryData.goodsName,
        orderNumber: this.queryData.orderNumber,
        isHideInvoice: this.queryData.isHideInvoice,
        isHideInvoiceInfo: this.queryData.isHideInvoiceInfo,
        invoiceType: this.queryData.invoiceType
      }
      let t = this.propsData.title
      let purchaseOrderStatus = this.queryData.purchaseOrderStatus == -1 ? undefined : this.queryData.purchaseOrderStatus
      if (t == '进项发票信息') {
        params.buyOrderStatus = purchaseOrderStatus
        params.buyType = this.billType
      }  else if (t == '销项发票信息') {
        params.orderStatus = purchaseOrderStatus
        params.orderType = this.billType
      } 
      return params
    },
    onRefresh() {
      this.queryData = this.$options.data().queryData
      this.queryData.xghCompanyId = this.xghCompany
      this.monthValue = '本月'
      this.getTimeRange(this.$setTimeRange(5))
      // if (this.propsData.title == '采购订单' || this.propsData.title == '销售订单') {
      //   this.queryData.status = '0'
      // } 
      this.getBillList()
    },
    getBillList (page) {
      // this.multipleBillSelection = []
      // this.multipleSelection = []
      let params = this.getParams()
      if (page == 1) {
        params.page = page
      }
      getAction(this.propsData.listUrl, params).then(res => {
        if (res.success) {
          let list = res.result || []
          console.log(11111111111,list);
          if (this.propsData.title == '') {
            this.listTableData = list.map(item => {
              item.orderTime = item.orderTime && item.orderTime.substring(0, 10)
              item.createOrderDate = item.createOrderDate.substring(0, 10)
              item.purchaseOrderPrice = formatMoney(item.purchaseOrderPrice)
              item.orderStatus = item[this.propsData.orderStatusKey]
              for (let index = 0; index < item[this.propsData.goodsListKey].length; index++) {
                const element = item[this.propsData.goodsListKey][index];
                element.orderId = item.id
                element.isGive_dictText = element.isGive ? element.isGive_dictText : element.isGift_dictText
                element.isGive = element.isGive || element.isGift
                element.salePrice = element.goodsPrice || element.salePrice
                element.remark = `调${this.propsData.title}${item.orderNumber};`
              }
              return item
            })
          } else if (this.propsData.title == '销售订单') {
            this.listTableData = list.map(item => {
              item.finishTime = item.finishTime && item.finishTime.substring(0, 10)
              item.deliverTime = item.deliverTime && item.deliverTime.substring(0, 10)
              item.orderStatus = item[this.propsData.orderStatusKey]
              item.status = item.performState
              for (let index = 0; index < item[this.propsData.goodsListKey].length; index++) {
                const element = item[this.propsData.goodsListKey][index];
                element.orderId = item.id
                element.isGive_dictText = element.isGive ? element.isGive_dictText : element.isGift_dictText
                element.isGive = element.isGive || element.isGift
                element.salePrice = element.goodsPrice || element.salePrice
                element.remark = `调${this.propsData.title}${item.orderNumber};`
                element.storeOrderNo = item.storeOrderNo
              }
              return item
            })
          }  else {
            this.listTableData = list.map((item) => {
              item.orderStatus = item[this.propsData.orderStatusKey]
              for (let index = 0; index < item[this.propsData.goodsListKey].length; index++) {
                const element = item[this.propsData.goodsListKey][index];
                element.orderId = item.id
                element.isGive_dictText = element.isGive ? element.isGive_dictText : element.isGift_dictText
                element.isGive = element.isGive || element.isGift
                element.salePrice = element.goodsPrice || element.salePrice
                // element.remark = `调${this.propsData.title}${item.orderNumber};`
              }
              return item
            })
          }
          console.log(this.listTableData);
          if (list.length) {
            this.detailTableData = list[0][this.propsData.goodsListKey]
            this.currentRow = list[0]
          } else {
            this.detailTableData = []
          }

          // 拿到明细后，给已选中的勾上

          this.$nextTick(() => {
            console.log('this.tabledata', this.detailTableData)
            console.log("this.propsData.selectedBills",this.propsData);

            // if(this.propsData.isNewOrder){

            // }
            // this.multipleSelection = JSON.parse(JSON.stringify(this.propsData.selectedDetails || []));
            // this.multipleBillSelection = JSON.parse(JSON.stringify(this.propsData.selectedBills || []));
        this.propsData.selectedBills.forEach(selectedBill => {
          const matchRow = this.listTableData.find(row => row.id === selectedBill.id);
              if (matchRow) {
                this.$refs.singleTable.toggleRowSelection(matchRow, true);
              }
        })
        this.propsData.selectedDetails.forEach(selectedBill => {
          const matchRow = this.detailTableData.find(row => row.id === selectedBill.id);
              if (matchRow) {
                this.$refs.multipleTable.toggleRowSelection(matchRow, true);
              }
        })
      })
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
    clearSelected () {
      console.log('清除选中22222');
      // 清空选中
      this.multipleSelection = []
      this.multipleBillSelection = []
      this.$nextTick(() => {
      this.$refs.singleTable.clearSelection();
      this.$refs.multipleTable.clearSelection();
      })
    },
    //废弃
    getBillDetail (id) {
      this.getDetailLoading = true
      getAction(this.propsData.detailUrl, { id }).then(res => {
        this.getDetailLoading = false
        if (res.success) {
          let result = res.result || {}
          let billObj = result[this.propsData.orderKey]
          let list = billObj[this.propsData.goodsListKey]
          if (this.propsData.title == '销售订单') {
            billObj.status = billObj.performState
            this.detailTableData = list.map(item => {
              item.isGive_dictText = item.isGive ? item.isGive_dictText : item.isGift_dictText
              item.isGive = item.isGive || item.isGift
              item.orderId = id
              item.salePrice = item.goodsPrice || item.salePrice
              item[this.propsData.orderKey] = billObj
              item.orderTime = billObj.orderTime
              item.orderNumber = billObj.orderNumber
              item.xghCompanyId_dictText = billObj.xghCompanyId_dictText
              item.sysUserId_dictText = billObj.sysUserId_dictText
              item.xghStorehouseId_dictText = billObj.xghStorehouseId_dictText
              item.isSupplement_dictText = billObj.isSupplement_dictText
              console.log(item);
              return item
            })
          } else {
            this.detailTableData = list.map(item => {
              item.isGive_dictText = item.isGive ? item.isGive_dictText : item.isGift_dictText
              item.isGive = item.isGive || item.isGift
              item.orderId = id
              item.salePrice = item.goodsPrice || item.salePrice
              item[this.propsData.orderKey] = billObj
              return item
            })
          }


          this.$nextTick(() => {
            this.detailTableData.forEach(row => {
              this.$refs.multipleTable.toggleRowSelection(row);
            });
          });
        } else {
          this.$elMessage.error(res.message)
        }
      }, err => {
        this.getDetailLoading = false
      })
    },
    // 单据单选
    handleSingleSelectionChange (val, row) {
      console.log("val",val,"row",row);
      let goodsList = row[this.propsData.goodsListKey]
      for (let i = 0; i < goodsList.length; i++) {
        let element = goodsList[i];
        console.log(element.id);
        console.log(val.includes(row));

        let index = this.getIndexById(element.id)
        if (val.includes(row) && index == -1) {
          this.multipleSelection.push(element)
          if (this.currentRow.id == element.orderId) {
            this.$refs.multipleTable.toggleRowSelection(element, true);
          }
        } else {
          this.multipleSelection.splice(index, 1)
          this.$refs.multipleTable.toggleRowSelection(element, false);

        }
      }
      console.log(this.multipleSelection);
      this.multipleBillSelection = val
    },
    //单据全选
    handleSingleSelectAll (val) {
      console.log(val);
      if (val.length) { //全选
        let mSelect = []
        let sSelect = []
        for (let index = 0; index < val.length; index++) {
          const row = val[index];
          mSelect.push(row)
          let goodsList = row[this.propsData.goodsListKey]
          for (let i = 0; i < goodsList.length; i++) {
            let element = goodsList[i];
            sSelect.push(element)
            if (this.currentRow.id == row.id) {
              this.$refs.multipleTable.toggleRowSelection(element, true);
            }
          }
        }
        this.multipleBillSelection = mSelect
        this.multipleSelection = sSelect
      } else { //全不选
        this.multipleBillSelection = []
        this.multipleSelection = []
        if (this.currentRow) {
          let goodsList = this.currentRow[this.propsData.goodsListKey]
          for (let i = 0; i < goodsList.length; i++) {
            let element = goodsList[i];
            this.$refs.multipleTable.toggleRowSelection(element, false);
          }
        }
      }
    },
    // 明细全选
    handleMultipleSelectAll (val) {
      console.log(val);
      if (val.length) {
        for (let i = 0; i < val.length; i++) {
          const row = val[i];
          let index = this.getIndexById(row.id)
          if (index == -1) {
            this.multipleSelection.push(row)
          }
        }
        this.changeParentCount(this.currentRow.id)
      } else {
        if (this.currentRow) {
          let goodsList = this.currentRow[this.propsData.goodsListKey]
          for (let i = 0; i < goodsList.length; i++) {
            let row = goodsList[i];
            let index = this.getIndexById(row.id)
            if (index > -1) {
              this.multipleSelection.splice(index, 1)
            }
            this.$refs.multipleTable.toggleRowSelection(row, false);
          }
          this.changeParentCount(this.currentRow.id)
        }
      }
    },

    handleMultipleSelect (val, row) {
      let index = this.getIndexById(row.id)
      if (index > -1) {
        this.multipleSelection.splice(index, 1)
      } else {
        this.multipleSelection.push(row)
      }
      this.changeParentCount(row.orderId)
      console.log(this.multipleSelection);
    },

    changeParentCount (id) {
      for (let index = 0; index < this.listTableData.length; index++) {
        const element = this.listTableData[index];
        if (element.id == id) {
          let list = element[this.propsData.goodsListKey]

          let count = 0
          for (let i = 0; i < list.length; i++) {
            const ele = list[i];
            let a = this.getIndexById(ele.id)
            if (a > -1) {
              count++
            }
          }
          if (count > 0) { //list.length == count
            this.$refs.singleTable.toggleRowSelection(element, true)
            this.changeSignleSelectionByItem(element, true)
          } else if (count == 0) {
            this.$refs.singleTable.toggleRowSelection(element, false)
            this.changeSignleSelectionByItem(element, false)
          }
        }
      }
    },
    // 增加或删除某条单据信息,add 选中true 取消false 
    changeSignleSelectionByItem (item, add) {
      let index = -1
      for (let i = 0; i < this.multipleBillSelection.length; i++) {
        const element = this.multipleBillSelection[i];
        if (element.id == item.id) {
          index = i
        }
      }
      if (index > -1) {
        if (!add) {
          this.multipleBillSelection.splice(index, 1)
        }
      } else {
        if (add) {
          this.multipleBillSelection.push(item)
        }
      }
    },
    // 判断所选明细数组是否包含某某条明细
    getIndexById (id) {
      for (let index = 0; index < this.multipleSelection.length; index++) {
        const element = this.multipleSelection[index];
        if (element.id == id) {
          return index
        }
      }
      return -1
    },
    async selectTitle () {
      let obj = await this.$setColumn.selectColumn(this.propsData.api)
      if (obj.code === 200) {
        this.updateId = obj.updateId
        this.columnData = obj.columnData
      } else if (obj.code === 500) {
        let id = await this.$setColumn.addColumn(this.propsData.api, this.columnData)
        this.updateId = id
      }
    },
    async selectDetailTitle () {
      let obj = await this.$setColumn.selectColumn(this.propsData.detailApi)
      if (obj.code === 200) {
        this.detailUpdateId = obj.updateId
        this.detailColumnData = handleObjectToArray(obj.columnData)
      } else if (obj.code === 500) {
        let id = await this.$setColumn.addColumn(this.propsData.detailApi, this.detailColumnData)
        this.detailUpdateId = id
      }
    },
    // 修改列配置后保存修改后的值
    async onSaveColumn (value) {
      let res = undefined
      if (this.columnSet == 'list') {
        this.columnData = value
        res = await this.$setColumn.editColumn(this.propsData.api, this.columnData, this.updateId)
      } else {
        this.detailColumnData = value
        res = await this.$setColumn.editColumn(this.propsData.detailApi, this.detailColumnData, this.detailUpdateId)
      }
      if (res.code == 200) {
        this.$elMessage.success(res.message)
      } else {
        this.$elMessage.error(res.message)
      }
    },
    // 打开列配置弹框
    onShowColumn (type) {
      if (type == 'list') {
        this.newColumnData = JSON.parse(JSON.stringify(this.columnData))
        this.defaultColumnData = billColumn.columnData[this.propsData.title].list
      } else {
        this.newColumnData = JSON.parse(JSON.stringify(this.detailColumnData))
        let detail = billColumn.columnData[this.propsData.title].detail
        this.defaultColumnData = handleObjectToArray(detail)
      }
      this.columnSet = type
      this.$refs.setColumnRef.dialogVisible = true
    },
    // 获取供应商
    getGysStorage () {
      getAction('/xghCompany/xghCompany/listNoPage', {}).then((res) => {
        if (res.code === 200) {
          let list = res.result || []
          this.gysOptions = [{
            companyName: '全部',
            id: '0'
          }].concat(list)
          this.totalCompanys = [{
            companyName: '全部',
            id: '0'
          }].concat(list)
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
    // 合计列计算
    getSummaries (param) {
      this.$nextTick(() => {
        this.$refs.singleTable.doLayout()
      })
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
        } else if (index === 1) {
          sums[index] = '共' + this.listTableData.length + '条'
        } else if (column.property == 'purchaseOrderPrice' || column.property == 'orderAllPrice' || column.property == 'allPrice' || column.property == 'receivablePrice' || column.property == 'number' || column.property == 'basicNumber' || column.property == 'salePrice' || column.property == 'taxUnitPrice' || column.property == 'taxPrice' || column.property == 'allPrice') {
          const values = data.map((item) => delcommafy(item[column.property]))
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = formatMoney(sums[index])
          }
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    // 合计列计算
    getSummaries1 (param) {
      this.$nextTick(() => {
        this.$refs.multipleTable.doLayout()
      })
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
        } else if (index === 1) {
          sums[index] = '共' + this.detailTableData.length + '条明细'
        } else if ( column.property == 'number' || column.property == 'basicNumber' || column.property == 'salePrice' || column.property == 'taxUnitPrice' || column.property == 'taxPrice' || column.property == 'allPrice') {
          const values = data.map((item) => delcommafy(item[column.property]))
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = formatMoney(sums[index])
          }
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    // 获取当前选中时间
    onClickPicker (val) {
      this.queryData.createTime_begin = val[0]
      this.queryData.createTime_end = val[1]
    },
    // 判断当前选择时间段
    changeDate (val) {
      switch (val) {
        case '全部':
          this.getTimeRange({
            now: '',
            end: ''
          })
          break
        case '今日':
          this.getTimeRange(this.$setTimeRange(1))
          break
        case '昨天':
          this.getTimeRange(this.$setTimeRange(2))
          break
        case '本周':
          this.getTimeRange(this.$setTimeRange(3))
          break
        case '上周':
          this.getTimeRange(this.$setTimeRange(4))
          break
        case '本月':
          this.getTimeRange(this.$setTimeRange(5))
          break
        case '上月':
          this.getTimeRange(this.$setTimeRange(6))
          break
        case '本年':
          this.getTimeRange(this.$setTimeRange(7))
          break
        case '去年':
          this.getTimeRange(this.$setTimeRange(8))
          break
        default:
          break
      }
    },
    // 获取时间范围并设置
    getTimeRange (data) {
      console.log(data);
      this.nowDate = [data.now, data.end]
      this.queryData.createTime_begin = data.now
      this.queryData.createTime_end = data.end
    },



    // 选中当前行
    onClickRow (row) {
      this.currentRow = row
      this.detailTableData = row[this.propsData.goodsListKey]
      this.$nextTick(() => {
        for (let index = 0; index < this.detailTableData.length; index++) {
          const element = this.detailTableData[index];
          let i = this.getIndexById(element.id)
          this.$refs.multipleTable.toggleRowSelection(element, i > -1);
        }
      });
    },
    // 双击选中当前行
    // onDblClickRow (row) {
    //   let goodsList = row[this.propsData.goodsListKey]
    //   this.multipleSelection = goodsList
    //   this.multipleBillSelection = [row]
    //   this.onSelectOrder()
    // },
    onSelectOrder () {
      if (!this.multipleBillSelection || this.multipleBillSelection.length == 0) {
        this.$elMessage.error('请选择单据信息！')
        return
      }
      let r = ''
      for (let index = 0; index < this.multipleBillSelection.length; index++) {
        const element = this.multipleBillSelection[index];
        console.log("element",JSON.parse(JSON.stringify(element)));
        if (element.orderStatus != 5) {
          this.$elMessage.warning("状态为'已审核'的单据才可以选择！")
          return
        }
        // if (element.invoicableOrderAmount <= 0 && element.invoicableOrderAmount != null) {
        //   this.$elMessage.warning("单据可开票金额为0，不可以开票！")
        //   return
        // }
        // if (element.invoiceStatus !== '未开票') {
        //   this.$elMessage.warning("状态为'未开票'的单据才可以选择！")
        //   return
        // }
        // if (element.status != 0 && this.showExecute) {
        //   this.$elMessage.warning('执行状态为‘未完成’的单据才可以选择！')
        //   return
        // }
        // r = r + `调${this.propsData.title}${element.orderNumber};`
      }

      for (let index = 0; index < this.multipleSelection.length; index++) {
        const goods = this.multipleSelection[index];
        console.log("商item品",goods.invoiceStatus,goods.invoiceStatus !== "未开票",goods);
        // if (goods.invoiceStatus !== "未开票") {
        //   this.$elMessage.warning(`商品：${goods.goodsName}已开票，请重新选择！`)
        //   return
        // }
        // if (element.invoiceStatus !== '未开票') {
        //   this.$elMessage.warning("状态为'未开票'的单据才可以选择！")
        //   return
        // }
        // if (element.status != 0 && this.showExecute) {
        //   this.$elMessage.warning('执行状态为‘未完成’的单据才可以选择！')
        //   return
        // }
        // r = r + `调${this.propsData.title}${element.orderNumber};`
      }

      
      // 创建单据ID与单据信息的映射关系
      let billMap = {}
      this.multipleBillSelection.forEach(bill => {
        billMap[bill.id] = {
          orderNumber: bill.orderNumber,
          orderDate: bill.orderTime || bill.createTime,
        }
      })
      
      // let obj = {
      //   ...this.multipleBillSelection[0],
      //   remark: r
      // }
      let list = this.multipleSelection.map((item) => {
        // console.log("商item品",item);
        item.callDocumentId = item.id
        item.callDocumentType = this.billType
        // 添加对应单据的日期和编号
        const billInfo = billMap[item.orderId || item.xghBuyOrderId]
        if (billInfo) {
          item.billNumber = billInfo.orderNumber
          item.billDate = billInfo.orderDate
        }
        // item.id = ''
        return item
      })
      let item = {
        billObj: this.multipleBillSelection,
        billName: this.propsData.title,
        goodsList: list
      }
      console.log("商品6666666666666",item);
      this.$emit('onSelectBill', item)
      this.hide()
    },
    //获取对应value
    getBillType () {
      let list = getDictItemsFromCache('document_type')
      let text = this.propsData.title
      for (let index = 0; index < list.length; index++) {
        const item = list[index];
        if (item.text == text) {
          return item.value
        }
      }
      return -1
    },
    // 打开新增客户弹出框
    onShowSupplierAdd () {
      this.$refs.supplierAddRef.dialogVisible = true
    },
    onAddSupplier (res) {
      this.getGysStorage()
    },
    // 打开选择客户弹出框
    onShowSupplier () {
      this.$refs.supplierRef.dialogVisible = true
    },
    // 当前选择客户数据
    onSelectSupplier (val) {
      this.queryData.xghCompanyId = val.id
    },
    handleFilterMethod (list, value, label) {
      this.gysOptions = this.filterMethod(list, value, label)
    }
  },
}
</script>

<style lang="scss" scoped>
.danju {
  display: flex;
  font-size: 14px;
  justify-content: space-between;
  color: #1993fb;
  height: 30px;
}

.sellOne {
  // margin-left: 0.281268rem;
  height: 1.875117rem;
}

::v-deep .el-dialog {
  width: 100%;

  // margin-top: 20vh !important;
  .el-dialog__body {
    padding: 0;
  }

  .el-dialog__header {
    width: 100%;
    height: 0.937559rem;
    box-sizing: border-box;
    padding: 0 0.187512rem 0 0.281268rem;
    border-bottom: 1px solid #eeeeee;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .el-dialog__headerbtn {
      position: static;

      .el-icon-close {
        color: #999;
        font-size: 0.48753rem;
      }
    }
  }

  .header_title {
    width: 100%;
    display: flex;
    align-items: center;

    .title_span {
      white-space: nowrap;
      font-size: 16px;
      color: #666;
      font-weight: 600;
    }
  }
}

.content_div {
  width: 100%;
  height: 70vh;
  min-height: 630px;
  background: #fff;
  box-sizing: border-box;
  padding: 0 20px 20px;
  display: flex;
  flex-direction: column;

  ::v-deep .el-table {
    border: 1px solid #e3e3e3;
    box-sizing: border-box;

    th,
    td {
      padding: 0;
      color: #666;
      box-sizing: border-box;
      border-right: 1px solid #e3e3e3;

      .cell {
        height: 30px;
        display: flex;
        align-items: center;
        font-size: 12px;
        justify-content: center;
      }

      &:last-child {
        border-right: none;
      }
    }

    th {
      .cell {
        background: #ededed;
        justify-content: center;
      }
    }

    .el-table__body tr:hover > td {
      background: #e3f6ff;
    }

    .el-table__footer-wrapper {
      td {
        background: #f4f4f4;
        border: none;
        padding: 0;

        .cell {
          margin: 0;
        }
      }
    }

    //滚动条的宽度
    ::-webkit-scrollbar {
      width: 10px;
      height: 10px;
      background-color: #e5e5e5;
    }

    //滚动条的滑块
    ::-webkit-scrollbar-thumb {
      background-color: #c9c9c9;
    }
  }
}

.div_screen {
  width: 100%;
  height: 100px;
  margin-top: 10px;
  // display: flex;
  // justify-content: space-between;

  .screen_left {
    font-size: 12px;
    box-sizing: border-box;
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    align-items: flex-start;
  }

  .screen_right {
    height: 40px;
    display: flex;
    align-items: center;
    // justify-content: center;
    .right_top {
      margin-right: 20px;
      box-sizing: border-box;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      box-sizing: border-box;
      padding-top: 10px;
    }

    ::v-deep .el-button {
      // width: 60px;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      border-radius: 5px;
      border: none;
    }
    .button-refresh {
      color: #1a93fa;
      border: 1px solid #1993fb;
    }
    ::v-deep .el-select {
      width: 80px;
      margin: 0 10px;

      .el-input {
        .el-input__inner {
          height: 30px;
          border-color: #e3e3e3;
          font-size: 12px;
          padding-left: 5px;
        }

        .el-input__suffix {
          height: 30px;
          display: flex;
          align-items: center;
        }
      }
    }

    ::v-deep .el-date-editor {
      width: 220px;
      height: 30px;
      background: #ffffff;
      border: 1px solid #d9d9d9;
      margin-right: 0.112507rem;
      padding: 3px 6px;

      .el-range__icon {
        position: absolute;
        right: 0;
        line-height: 30px;
      }

      .el-range-separator {
        line-height: 24px;
      }

      .el-range-input {
        font-size: 12px;
      }

      .el-range__close-icon {
        display: none;
      }
    }
  }
}

.table_pagination {
  width: 100%;
  height: 1.12507rem;
  box-sizing: border-box;
  padding: 0.168761rem 0;
  display: flex;

  .pagination_div {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-end;

    ::v-deep .el-pagination {
      padding: 0;
      height: 0.525033rem;

      .el-pagination__sizes {
        margin: 0;

        .el-input {
          margin-right: 0;
        }
      }
    }
  }
}

.custom_item {
  display: flex;
  align-items: center;
  margin: 10px 10px 10px 0;
  width: 180px;
  font-size: 12px;
}

.custom_select_head {
  flex: 1;
  height: 30px;
  position: relative;

  ::v-deep .el-select {
    .el-input {
      .el-input__inner {
        height: 30px;
        border-color: #e3e3e3;
        font-size: 12px;
        padding-left: 5px;
      }

      .el-input__suffix {
        height: 30px;
        display: flex;
        align-items: center;
      }
    }
  }

  ::v-deep .el-input {
    width: 100%;

    .el-input__inner {
      height: 30px;
      border-color: #e3e3e3;
      font-size: 12px;
      padding-left: 5px;
    }

    .el-input__suffix {
      height: 30px;
      display: flex;
      align-items: center;
    }
  }
}

.custom_more {
  position: absolute;
  right: 10px;
  z-index: 10;
  top: 1px;
  background: #fff;
  height: 28px;
  display: flex;
  align-items: center;
  color: #bfbfbf;
}

.custom_add {
  display: flex;
  justify-content: center;
  align-items: center;

  span {
    margin-left: 5px;
    color: #666666;
  }

  i {
    color: #666666;
  }
}
</style>